//
//  MineViewController.m
//  MiAiApp
//
//  Created by voidcat on 2017/5/18.
//  Copyright © 2017年 voidcat. All rights reserved.
//

#import "CYMineViewController.h"
#import "MineTableViewCell.h"
#import "MineHeaderView.h"
#import "ProfileViewController.h"
#import "SettingViewController.h"
#import "ProtocolViewController.h"
#import "MineEditUserInfoViewController.h"
#import "SettingViewController.h"
#import "XYTransitionProtocol.h"
#import "RootWebViewController.h"
#import "MineLogic.h"
#import "AuthVideoViewController.h"
//tableview cell
#import "MineHeaderCell.h"
#import "MineCoinTableViewCell.h"
#import "MineBuyCoinTableViewCell.h"
#import "MianiRewardTableViewCell.h"
#import "MineMenuView.h"
#import "PrivatePhotosViewController.h"
#import "FansBaseViewController.h"
#import "MyVideoViewController.h"
#import "MineWealthViewController.h"
#import "RechargeViewController.h"
#import "InviteViewController.h"
#import "CooperationViewController.h"
#import "UserInfoViewController.h"
#import "AuthenticationViewController.h"
//model
#import "EditUserModel.h"
#define KHeaderHeight ((260 * Iphone6ScaleWidth) + kStatusBarHeight)

@interface CYMineViewController ()<QMUITableViewDelegate,QMUITableViewDataSource,headerViewDelegate,XYTransitionProtocol,MineHeaderCellDelegate,MineDelegate>
{
    UILabel * lbl;
    NSArray *_dataSource;
    NSArray *_listArray;
    MineHeaderView *_headerView;//头部view
    UIView *_NavView;//导航栏
    MineMenuView *menuView;
    MineLogic *_logic;
}
@end

@implementation CYMineViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.isHidenNaviBar = YES;
    self.StatusBarStyle = UIStatusBarStyleLightContent;
    self.isShowLiftBack = NO;//每个根视图需要设置该属性为NO，否则会出现导航栏异常
    self.title = ASLocalizedString(@"我的");
    _logic = [[MineLogic alloc] init];
    _logic.delegagte = self;
    [_logic loadData];
    [self createUI];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.tableView.frame = CGRectMake(0, kTopHeight, KScreenWidth, kScreenHeight - kTopHeight - self.qmui_tabBarSpacingInViewCoordinator - 40);
    self.navigationController.navigationBar.hidden = YES;
    [self getRequset];
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    //    self.navigationController.delegate = self.navigationController;
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    //    [self ysl_removeTransitionDelegate];
}

#pragma mark ————— 拉取数据 —————
-(void)getRequset{
    [[EditUserModel new] updateUserinfo:^(BOOL success) {
        [userManager loadUserInfo];
        NSLog(@"curUser.user_nickname %@",curUser.user_nickname);
        [self performSelectorOnMainThread:@selector(updateUI) withObject:nil waitUntilDone:NO];
    }];
    
    [_logic loadData];
}

-(void)updateUI
{
    [self.tableView reloadData];
}

#pragma mark ————— 头像被点击 —————
-(void)headerViewClick{
    //    [self ysl_addTransitionDelegate:self];
    ProfileViewController *profileVC = [ProfileViewController new];
    profileVC.headerImage = _headerView.headImgView.image;
    [self.navigationController pushViewController:profileVC animated:YES];
}

#pragma mark ————— 昵称被点击 —————
-(void)nickNameViewClick{
    [self.navigationController pushViewController:[RootViewController new] animated:YES];
}

#pragma mark -- YSLTransitionAnimatorDataSource
//-(UIImageView *)pushTransitionImageView{
//    return _headerView.headImgView;
//}
//
//- (UIImageView *)popTransitionImageView
//{
//    return nil;
//}
-(UIView *)targetTransitionView{
    return _headerView.headImgView;
}
-(BOOL)isNeedTransition{
    return YES;
}


#pragma mark ————— 创建页面 —————
-(void)createUI{
    self.view.backgroundColor = CF6;
    self.tableView.backgroundColor = CF6;
    self.tableView.height = KScreenHeight - kTabBarHeight;
    self.tableView.mj_header.hidden = YES;
    self.tableView.separatorColor = CF6;
    self.tableView.mj_footer.hidden = YES;

    [self.tableView registerClass:[MineTableViewCell class] forCellReuseIdentifier:@"MineTableViewCell"];
    
    //注册头部
    [self.tableView registerNib:[UINib nibWithNibName:[MineHeaderCell className] bundle:nil] forCellReuseIdentifier:[MineHeaderCell className]];
    
    //注册财富
    [self.tableView registerNib:[UINib nibWithNibName:[MineCoinTableViewCell className] bundle:nil] forCellReuseIdentifier:[MineCoinTableViewCell className]];
    
    //注册购买聊币
    [self.tableView registerNib:[UINib nibWithNibName:[MineBuyCoinTableViewCell className] bundle:nil] forCellReuseIdentifier:[MineBuyCoinTableViewCell className]];
    
    //注册赠送钻石
    [self.tableView registerNib:[UINib nibWithNibName:[MianiRewardTableViewCell className] bundle:nil] forCellReuseIdentifier:[MianiRewardTableViewCell className]];

    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
//    _headerView = [[MineHeaderView alloc] initWithFrame:CGRectMake(0, -KHeaderHeight, KScreenWidth, KHeaderHeight)];
//    _headerView.delegate = self;
    [self createNav];
    [self.view addSubview:self.tableView];


    
    NSArray *l1 = [NSArray arrayWithObjects:ASLocalizedString(@"头部"), nil];
//    NSArray *l2 = [NSArray arrayWithObjects:ASLocalizedString(@"财富"), nil];
    NSArray *l3 = [NSArray arrayWithObjects:ASLocalizedString(@"购买"), nil];
    NSArray *l4 = [NSArray arrayWithObjects:ASLocalizedString(@"周卡奖励"), nil];
//    _listArray = [NSArray arrayWithObjects:l1,l2,l3,l4,nil];
    _listArray = [NSArray arrayWithObjects:l1,l4,nil];

    @weakify(self);
    menuView = [[MineMenuView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 240)];
    menuView.backgroundColor = KWhiteColor;
    menuView.itemClick = ^(long index) {
        [weak_self menuViewItemClickWithIndex:index];
    };
    self.tableView.tableFooterView = menuView;
    [self.tableView reloadData];
}

#pragma mark ————— 创建自定义导航栏 —————
-(void)createNav{
    _NavView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, kTopHeight)];
    _NavView.backgroundColor = KWhiteColor;
//    UIView *line = [[UIView alloc] init];
//    line.backgroundColor = CF6;
//    line.frame = CGRectMake(0,kTopHeight - 2, KScreenWidth , 2);
//    [_NavView addSubview:line];
    
    UILabel * titlelbl = [[UILabel alloc] initWithFrame:CGRectMake(0, kStatusBarHeight, KScreenWidth/2, kNavBarHeight )];
    titlelbl.centerX = _NavView.width/2;
    titlelbl.textAlignment = NSTextAlignmentCenter;
    titlelbl.font= SYSTEMFONT(17);
    titlelbl.textColor = KBlackColor;
    titlelbl.text = ASLocalizedString(@"我的");
    [_NavView addSubview:titlelbl];
    
    UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
//    [btn setTitle:@"" forState:UIControlStateNormal];
    btn.titleLabel.font = SYSTEMFONT(16);
    [btn setTitleColor:KWhiteColor forState:UIControlStateNormal];
    [btn sizeToFit];
    btn.frame = CGRectMake(_NavView.width - btn.width - 15, kStatusBarHeight, btn.width, 40);
    btn.contentMode = UIViewContentModeScaleAspectFit;
    [btn setImage:[UIImage imageNamed:@"mine_edit"] forState:UIControlStateNormal];
    [btn setTitleColor:KWhiteColor forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(editUserInfo) forControlEvents:UIControlEventTouchUpInside];
    
    [_NavView addSubview:btn];
    
    [self.view addSubview:_NavView];
}

#pragma mark ————— tableview 代理 —————
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [[_listArray objectAtIndex:section] count];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
     return _listArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSString *cellName = [[_listArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    
    if([cellName isEqualToString:ASLocalizedString(@"头部")])
    {
        return 180;
    }
    else if([cellName isEqualToString:ASLocalizedString(@"购买")])
    {
        return 50;

//        return 120;
    }
    else if([cellName isEqualToString:ASLocalizedString(@"周卡奖励")])
    {
        return 0;
    }
    
    return 50.0f;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSString *cellName = [[_listArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    
    if([cellName isEqualToString:ASLocalizedString(@"头部")])
    {
        MineHeaderCell *cell = [tableView dequeueReusableCellWithIdentifier:[MineHeaderCell className]];
        cell.delegae = self;
        [cell setModel:_logic.model];
        [cell updateData];
        return cell;
    }
    
    if([cellName isEqualToString:ASLocalizedString(@"财富")])
    {
        MineCoinTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[MineCoinTableViewCell className]];
        [cell setModel:_logic.model];
        return cell;
    }
    
    if([cellName isEqualToString:ASLocalizedString(@"购买")])
    {
        MineBuyCoinTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[MineBuyCoinTableViewCell className]];
        if(!(_logic.model == nil))
        {
            [cell setPayCoin:_logic.model.pay_coin];
        }
        return cell;
    }
    
    if([cellName isEqualToString:ASLocalizedString(@"周卡奖励")])
    {
        MianiRewardTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[MianiRewardTableViewCell className]];
        cell.hidden = YES;
        return cell;
    }
    
    MineTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MineTableViewCell" forIndexPath:indexPath];
//    cell.cellData = _dataSource[indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSString *cellName = [[_listArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    if([cellName isEqualToString:ASLocalizedString(@"财富")])
    {
        MineWealthViewController *mineWealth = [[MineWealthViewController alloc] init];
        [self.navigationController pushViewController:mineWealth animated:YES];
    }
    else if([cellName isEqualToString:ASLocalizedString(@"购买")])
    {
        RechargeViewController *recharge = [RechargeViewController new];
        recharge.title = ASLocalizedString(@"充值");
        [self.navigationController pushViewController:recharge animated:NO];
    }
    else if([cellName isEqualToString:ASLocalizedString(@"头部")])
    {
        UserInfoViewController *recharge = [UserInfoViewController new];
//        recharge.isHidenNaviBar = YES;
        recharge.uid = curUser.id;
        [self.navigationController pushViewController:recharge animated:NO];
    }
}

-(void)MineHeaderClick
{
    UserInfoViewController *recharge = [UserInfoViewController new];
    recharge.uid = curUser.id;
    [self.navigationController pushViewController:recharge animated:NO];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 2;
}
#pragma mark ————— scrollView 代理 —————
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGFloat offset = scrollView.contentOffset.y ;
    CGFloat totalOffsetY = scrollView.contentInset.top + offset;
    
    NSLog(@"offset    %.f   totalOffsetY %.f",offset,totalOffsetY);
    //    if (totalOffsetY < 0) {
    _headerView.frame = CGRectMake(0, offset, self.view.width, KHeaderHeight- totalOffsetY);
    //    }
    
}
#pragma mark - 头部粉丝，关注，分成比例点击事件
-(void)MineHeaderClickItemWithType:(CYMineClickType)type
{
    switch (type) {
        case CYMineClickTypeLeft:
            [self gotoAttrVC];
            break;
        case CYMineClickTypeCenter:
            [self gotoFansVC];
            break;
        case CYMineClickTypeRight:
            [self gotoRate];//跳转分成页面
        default:
            break;
    }
}

//跳往关注页面
-(void)gotoAttrVC
{
    FansBaseViewController *fans = [FansBaseViewController new];
    fans.type = CYFansTypeAttr;
    [self.navigationController pushViewController:fans animated:YES];
}
//跳往粉丝页面
-(void)gotoFansVC
{
    FansBaseViewController *fans = [FansBaseViewController new];
    fans.type = CYFansTypeFans;
    [self.navigationController pushViewController:fans animated:YES];
}

//gotoRate
-(void)gotoRate
{
    
//    XLWebViewController *webview = [[XLWebViewController alloc] initWithUrl:KGlobalVariable.appmodel.app_h5.];

}
#pragma mark ————— 切换账号 —————
-(void)changeUser{
    SettingViewController *settingVC = [SettingViewController new];
    [self.navigationController pushViewController:settingVC animated:YES];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 跳转到个人中心
-(void)editUserInfo
{
    MineEditUserInfoViewController *editUserInfo = [[MineEditUserInfoViewController alloc] init];
    [self.navigationController pushViewController:editUserInfo animated:YES];
}

- (void)menuViewItemClickWithIndex:(long)index {
    NSArray *arr = MENU_ITEM;
    NSString *itemStr = arr[index];

    if([itemStr isEqualToString:ASLocalizedString(@"设置")])
    {
        [self jumpSeting];
        return;
    }
    else if([itemStr isEqualToString:ASLocalizedString(@"私照")])
    {
        PrivatePhotosViewController *privtePhoto = [PrivatePhotosViewController new];
        privtePhoto.touid = curUser.id;
        [self.navigationController pushViewController:privtePhoto animated:NO];
        
        return;
    }
    else if([itemStr isEqualToString:ASLocalizedString(IsCurrentUserMale ? @"实名认证" : @"成为主播")])
    {
        if(_logic.model.user_auth_status == 0 )
        {
            [[HUDHelper sharedInstance] tipMessage:ASLocalizedString(@"审核中")];
            return;
        }

        if(_logic.model.user_auth_status == 1)
        {
            [[HUDHelper sharedInstance] tipMessage:ASLocalizedString(@"您已通过审核")];
            return;
        }
        
        if (IsCurrentUserMale) {
            AuthenticationViewController *vc = [AuthenticationViewController new];
            vc.title = ASLocalizedString(IsCurrentUserMale ? @"实名认证" : @"成为主播");
            [self.navigationController pushViewController:vc animated:NO];
        } else {
            ProtocolViewController *vc = [[ProtocolViewController alloc] init];
            [self.navigationController pushViewController:vc animated:NO];
        }
//        VideoConfigure* _videoConfig = [[VideoConfigure alloc] init];
//        AuthVideoViewController *authVC = [[AuthVideoViewController alloc] initWithConfigure:_videoConfig];
//        [self.navigationController pushViewController:authVC animated:YES];
        return;
    }
    else if([itemStr isEqualToString:ASLocalizedString(@"小视频")])
    {
        MyVideoViewController *myVideo = [[MyVideoViewController alloc] init];
        [self.navigationController pushViewController:myVideo animated:YES];
        return;
    }
//    else if([itemStr isEqualToString:ASLocalizedString(@"邀请好友")])
//    {
//        InviteViewController *vc = [[InviteViewController alloc] init];
//        [self.navigationController pushViewController:vc animated:YES];
//        return;
//    }
    else if([itemStr isEqualToString:ASLocalizedString(@"主播/工会合作")])
    {
        CooperationViewController *vc = [[CooperationViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
        return;
    }
    else if([itemStr isEqualToString:ASLocalizedString(@"钱包")])
    {
        MineWealthViewController *mineWealth = [[MineWealthViewController alloc] init];
        [self.navigationController pushViewController:mineWealth animated:YES];
        return;
    }
    int f = 0;
    //以下跳转h5
    RootWebViewController *webview = [RootWebViewController new];
    
    NSString *urlstring;

    if([itemStr isEqualToString:ASLocalizedString(@"新手引导")])
    {
        urlstring = KGlobalVariable.appmodel.app_h5.newbie_guide;
    }
    else if([itemStr isEqualToString:ASLocalizedString(@"我的等级")])
    {
        urlstring = KGlobalVariable.appmodel.app_h5.my_level;
    }
    else if([itemStr isEqualToString:ASLocalizedString(@"邀请好友")])
    {
        urlstring = KGlobalVariable.appmodel.app_h5.invite_friends;
    }
    else
    {
        f = 1;
//        [[HUDHelper sharedInstance] tipMessage:ASLocalizedString(@"功能开发中.")];
    }
    if(f != 1)
    {
        [self jumpwebviewWithIndex:index];
//        urlstring = [NSString stringWithFormat:@"%@?uid=%@&token=%@",urlstring,curUser.id,curUser.token];
//        webview.url = urlstring;
//        [self.navigationController pushViewController:webview animated:YES];
    }

    
    
}

-(void)jumpwebviewWithIndex:(NSInteger )index
{
    NSArray *arr = MENU_ITEM;
    RootWebViewController *webview = [RootWebViewController new];
    NSString *itemStr = arr[index];
    
    NSString *urlstring;
    if([itemStr isEqualToString:ASLocalizedString(@"邀请好友")])
    {
        urlstring = KGlobalVariable.appmodel.app_h5.invite_share_menu;
    }
    else if([itemStr isEqualToString:ASLocalizedString(@"新手引导")])
    {
        urlstring = KGlobalVariable.appmodel.app_h5.newbie_guide;
    }
    else if([itemStr isEqualToString:ASLocalizedString(@"我的等级")])
    {
        urlstring = KGlobalVariable.appmodel.app_h5.my_level;
    }
    
    urlstring = [NSString stringWithFormat:@"%@?uid=%@&token=%@",urlstring,curUser.id,curUser.token];
    webview.url = urlstring;
    [self.navigationController pushViewController:webview animated:YES];
}
-(void)jumpSeting
{
    SettingViewController *vc = [SettingViewController new];
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark - 数据加载完成回调
-(void)requestDataCompleted
{
    NSString *statusTip;
    switch (_logic.model.user_auth_status) {
        case -1:
            statusTip = ASLocalizedString(@"未提交");
            break;
        case 0:
            statusTip = ASLocalizedString(@"审核中");
            break;
        case 1:
            statusTip = ASLocalizedString(@"已通过");
            break;
        case 2:
            statusTip = ASLocalizedString(@"审核未通过");
            break;
        default:
            break;
    }
    curUser.level = _logic.model.level;
    curUser.is_open_do_not_disturb = _logic.model.is_open_do_not_disturb;
    
    menuView.tipArr = @[statusTip,@"",@"",@"",@"",@"",@"",@"",@""];
    [self.collectionView reloadData];
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end

